package cn.tedu.mvc.service.impl;

import cn.tedu.mvc.dao.UserDao;
import cn.tedu.mvc.entity.User;
import cn.tedu.mvc.exception.*;
import cn.tedu.mvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl implements UserService {

    UserDao userDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    @Transactional
    public User regist(String username, String password) {
        if (username==null || password==null) {
            throw new IllegalParameterException("参数异常！");
        }

        User user = userDao.getUserByName(username);
        if (user!=null) {
            throw new UsernameExistException("该用户名已经被注册！");
        }
        user = new User();
        user.setUsername(username);
        user.setPassword(password);
        int i = userDao.addUser(user);
        System.out.println(i);
        if (i!=1) {
            throw new RegistFaildException("注册用户失败！");
        }
        return user;
    }

    @Override
    @Transactional
    public User login(String username, String password) {
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            throw new IllegalParameterException("用户名密码不能为空！");
        }
        User user = userDao.getUserByName(username);

        if (user==null) {
            throw new UserNotFoundException("该用户不存在！");
        }
        if (!user.getPassword().equals(password)) {
            throw new PasswordErrorException("密码错误！");
        }
        return user;
    }

    @Override
    public User findUser(String username) {
        return userDao.getUserByName(username);
    }

    @Override
    public User findUser(Integer userid) {
        return userDao.getUserById(userid);
    }
}
